//201902104003邵潇漩
package bysj.controller.basic;

import bysj.domain.Department;
import bysj.exception.BysjException;
import bysj.service.DepartmentService;
import bysj.service.SchoolService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
/**
 * @author 邵潇漩
 * @version 1.0  11-13-2020
 */

@Slf4j
@WebServlet("/department.ctl")
public class DepartmentController extends HttpServlet {
    /**
     * POST, http://localhost:8080/department.ctl, 增加系
     * 增加一个系对象：将来自前端请求的JSON对象，增加到数据库表中
     *
     *  {"description":"信管",no:"0206","remarks":"","school_id":2}
     *
     * @param request  请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        //request.setCharacterEncoding("UTF-8");
        //根据request对象，获得代表参数的JSON字串
        String department_json = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(department_json);
        //将JSON字串解析为Department对象
        Department departmentToAdd = JSON.parseObject(department_json, Department.class);
        //设置响应字符编码为UTF-8
        //response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加Department对象
        try {
            //从JSONObject对象中读取键“school_id”的值
            Object schoolId_obj = req_jsonObj.get("school_id");
            int schoolId_int = Integer.parseInt(schoolId_obj.toString());
            departmentToAdd.setSchool(SchoolService.getInstance().find(schoolId_int));
            DepartmentService.getInstance().add(departmentToAdd);
            message.put("message", "增加成功");
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            log.error("数据库操作异常:"+e);
        } catch (Exception e) {
            message.put("message", "网络异常");
            log.error("网络异常:"+e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    /**
     * DELETE, http://localhost:8080/department.ctl, 删除id=1的系
     * 删除一个系对象：根据来自前端请求的id，删除数据库表中id的对应记录
     *
     * {"id":1}
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
        Object id_obj = req_jsonObj.get("id");
        int id_int = Integer.parseInt(id_obj.toString());
        //设置响应字符编码为UTF-8
        //response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表中删除对应的系
        try {
            DepartmentService.getInstance().delete(id_int);
            message.put("message", "删除成功");
        }catch (BysjException e) {
            message.put("message", e.getMessage());
            log.error("Bysj异常:"+e);
        }catch (SQLException e) {
            message.put("message", "数据库操作异常");
            log.error("数据库操作异常:"+e);
        }catch (Exception e) {
            message.put("message", "网络异常");
            log.error("网络异常:"+e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }


    /**
     * PUT, http://localhost:8080/department.ctl, 修改系
     *
     *  {"id":6,"description":"信管",no:"0206","remarks":"xx","school_id":2}
     *
     * 修改一个系对象：将来自前端请求的JSON对象，更新数据库表中相同id的记录     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        //request.setCharacterEncoding("UTF-8");
        String department_json = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(department_json);
        //将JSON字串解析为Department对象
        Department department = JSON.parseObject(department_json, Department.class);
        //设置响应字符编码为UTF-8
        //response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表修改Department对象对应的记录
        try {
            //从JSONObject对象中读取键“school_id”的值
            Object schoolId_obj = req_jsonObj.get("school_id");
            int schoolId_int = Integer.parseInt(schoolId_obj.toString());
            department.setSchool(SchoolService.getInstance().find(schoolId_int));
            DepartmentService.getInstance().update(department);
            message.put("message", "修改成功");
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            log.error("数据库操作异常:"+e);
        } catch (Exception e) {
            message.put("message", "网络异常");
            log.error("网络异常:"+e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    /**
     * GET, http://localhost:8080/department.ctl, 查询所有的系
     * 把一个或所有系对象响应到前端
     *
     *可能的请求
     *     {"id":1}
     *     可能的请求
     *    {
     *         "pagination": {
     *         "pageNo": 1,
     *         "pageSize": 2
     *         },
     *         "conditionList": [{
     *             "value": "管",
     *             "key": "description",
     *             "operator": "LIKE"
     *             },
     *             {
     *             "value": "2",
     *             "key": "school_id",
     *             "operator": "="
     *             }
     *         ]
     *     }
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
        //response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            return;
        }
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
        Object id_obj = req_jsonObj.get("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个系对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseDepartment(id_int, response);
                log.info("id="+id_int);
            } else {//请求中包含条件和分页信息，需要响应多个系对象
                //读取分页信息，形成分页对象
                //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
                List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
                //响应多个系信息，其中conditionList, pagination两个对象引用为空是可能的
                this.responseDepartments(response, pagination,conditionList);
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error("数据库操作异常:"+e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error("网络异常:"+e);
        }
    }


    //响应一个系对象
    private void responseDepartment(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找系
        Department department = DepartmentService.getInstance().find(id);
        String department_json = JSON.toJSONString(department);
        //响应department_json到前端
        response.getWriter().println(department_json);
    }

   //响应所有系对象
   private void responseDepartments(HttpServletResponse response,Pagination pagination,List<Condition> conditionList)
           throws ServletException, IOException, SQLException {
       //获得满足条件的所有系
       Collection<Department> departments = DepartmentService.getInstance().findAll(pagination,conditionList);
       String department_json = JSON.toJSONString(departments,SerializerFeature.DisableCircularReferenceDetect);
       JSONObject response_json = new JSONObject();
       response_json.put("totalNum" ,pagination.getTotalNum());
       response_json.put("data",department_json);
       //响应response_json到前端
       response.getWriter().println(response_json);
   }
}
